package com.jeff.client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import android.util.Log;

public class EchoClient {
	private String ip = "127.0.0.1";
	private int port = 9527;
	private PrintWriter pw = null;
	private BufferedReader br = null;
	
	public EchoClient(String ip, int port) {
		this.ip = ip;
		this.port = port;
	}
	
	public boolean init() {
		try {
			Socket server = new Socket(ip,port);
			br = new BufferedReader(new InputStreamReader(server.getInputStream()));
			pw = new PrintWriter(server.getOutputStream(),true);
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
		return true;
	}
	
	public boolean sendMsg(String msg) {
		if(pw == null) {
			if(!init()) {
				return false;
			}
		}
		Log.i("yao", "send msg in echo client");
		pw.println(msg);
		return true;
	}

	public String receiveMsg() {
		if(br == null) {
			if(!init()) {
				return null;
			}
		}
		String line;
		try {
			line = br.readLine();
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
		return line;
	}
	
	public String getIp() {
		return ip;
	}

	public void setIp(String ip) {
		this.ip = ip;
	}

	public int getPort() {
		return port;
	}

	public void setPort(int port) {
		this.port = port;
	}
	
}
